package com.LeeCode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树的前序遍历
 */

public class Code144 {
    public static void main(String[] args) {
        Integer[] arr = new Integer[]{1, null, 2, 3};
        TreeNode root = Utils.buildTree(arr);
        System.out.println(new Code144().preorderTraversal(root));
    }

    List<Integer> ans = new ArrayList();

    public List<Integer> preorderTraversal(TreeNode root) {
        preorder(root);
        return ans;
    }

    private void preorder(TreeNode root) {
        if (root == null) return;
        ans.add(root.val);
        preorder(root.left);
        preorder(root.right);
    }

    public List<Integer> preorderTraversal1(TreeNode root) {
        List<Integer> ans = new ArrayList();

        if (root == null) return ans;

        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode node = root;
        while(!stack.isEmpty() || node != null) {
            while(node != null) {
                ans.add(node.val);
                stack.push(node);
                node = node.left;
            }
            node = stack.pop();
            node = node.right;
        }
        return ans;
    }
}
